package com.adminx.security;

import java.util.Collection;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;


public class MyAccessDecisionManager implements AccessDecisionManager{
	
	private static Logger LOGGER = Logger.getLogger(MyAccessDecisionManager.class);
	
	/**
	 * 权限验证
	 */
	@Override
	public void decide(Authentication authentication, Object obj, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		Iterator<ConfigAttribute> it = configAttributes.iterator();
		while(it.hasNext()){
			ConfigAttribute co = it.next();
			String role = co.getAttribute();
			String path = obj.toString();
			for(GrantedAuthority grantedAuthority:authentication.getAuthorities()){
				if(role.equals(grantedAuthority.getAuthority())){
					LOGGER.info("【安全框架】资源:"+path.substring(path.indexOf("URL: ")+5,path.length())+"权限验证通过！");
					return;
				}
			}
			LOGGER.info("【安全框架】资源:"+path.substring(path.indexOf("URL: ")+5,path.length())+"无权访问!");
			//解除注释，若无权限，将被跳转
			throw new AccessDeniedException("【安全框架】你无权访问这个资源，跳至登录页面。");
		}
	}
	
	/**
	 * 必须返回true，否则报错
	 */
	@Override
	public boolean supports(ConfigAttribute arg0) {
		// TODO Auto-generated method stub
		return true;
	}
	
	/**
	 * 必须返回true，否则报错
	 */
	@Override
	public boolean supports(Class<?> arg0) {
		// TODO Auto-generated method stub
		return true;
	}

}
